package com.usefullc.english.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.usefullc.common.util.BeanUtils;
import com.usefullc.common.util.TimeUtils;
import com.usefullc.english.domain.Subtitle;
import com.usefullc.english.domain.UserSubtitle;
import com.usefullc.english.domain.UserWordDict;
import com.usefullc.english.mapper.SubtitleMapper;
import com.usefullc.english.query.SubtitleQuery;
import com.usefullc.english.query.UserSubtitleQuery;
import com.usefullc.english.query.UserWordDictQuery;
import com.usefullc.english.vo.SingleWordDictVo;
import com.usefullc.english.vo.SubtitleVo;
import com.usefullc.english.vo.WordDictVo;
import com.usefullc.system.entity.Pager;
import com.usefullc.system.service.AbstractBizService;
import com.usefullc.user.service.component.UserManager;
import com.usefullc.user.vo.UserVo;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Time;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 字幕服务类
 * @author: 星空
 * @date: 2022-08-07
 */
@Service
public class SubtitleService extends AbstractBizService<SubtitleMapper, Subtitle, SubtitleQuery> {

    @Autowired
    private UserWordDictService userWordDictService;

    @Autowired
    private UserSubtitleService userSubtitleService;

    @Override
    protected QueryWrapper<Subtitle> getQueryWrapper(SubtitleQuery query) {
        QueryWrapper<Subtitle> queryWrapper = super.getQueryWrapper(query);
        return queryWrapper;
    }

    public Pager<SubtitleVo> findVoByPage(SubtitleQuery query){
        Pager<Subtitle> page = this.findByPage(query);
        Pager<SubtitleVo> newPage = new Pager<>(page);
        List<Subtitle> dataList = page.getDataList();
        List<SubtitleVo> newDataList = new ArrayList<>();
        newPage.setDataList(newDataList);
        for (Subtitle subtitle : dataList) {
            SubtitleVo subtitleVo = BeanUtils.beanCopy(subtitle, SubtitleVo.class);
            newDataList.add(subtitleVo);
        }
        return newPage;
    }


    public List<SubtitleVo> findAllVo(SubtitleQuery query){
        List<Subtitle> dataList = this.findAll(query);
        List<SubtitleVo> newDataList = new ArrayList<>();
        for (Subtitle subtitle : dataList) {
            SubtitleVo subtitleVo = BeanUtils.beanCopy(subtitle, SubtitleVo.class);
            Time gmtStart = subtitle.getGmtStart();
            String starTime = DateFormatUtils.format(gmtStart,"HH:mm:ss.S");
            long startTimeMs = TimeUtils.formatTime2MillSeconds(starTime);
            subtitleVo.setStartTimeMs(startTimeMs);

            Time gmtEnd = subtitle.getGmtEnd();
            String endTime = DateFormatUtils.format(gmtEnd, "HH:mm:ss.S");
            long endTimeMs = TimeUtils.formatTime2MillSeconds(endTime);
            subtitleVo.setEndTimeMs(endTimeMs);

            //单词列表
            List<SingleWordDictVo> singleWordDictList = new ArrayList<>();
            subtitleVo.setSingleWordDictList(singleWordDictList);
            String enText = subtitleVo.getEnText();
            if(StringUtils.isEmpty(enText)){
                continue;
            }
            String[] wordList = enText.split("\\s+");
            for (String word : wordList) {

                if(word.length() == 0){
                    continue;
                }

                //前面特殊字符处理
                String ch = word.substring(0, 1);
                String alpha = "[a-zA-Z]";
                logger.info("word="+word);
                while (!ch.matches(alpha)) {
                    word = word.substring(1);
                    if(word.length() == 0){
                        break;
                    }
                    SingleWordDictVo singleWordDictVo = new SingleWordDictVo();
                    singleWordDictVo.setName(ch);
                    singleWordDictVo.setSpecialChar(true);
                    singleWordDictList.add(singleWordDictVo);
                    ch = word.substring(0, 1);
                }
                if(word.length() != 0){
                    //后面特殊字符处理
                    List<SingleWordDictVo> backSingleWordDictList = new ArrayList<>();
                    ch = word.substring(word.length()-1, word.length());
                    while (!ch.matches(alpha)) {
                        word = word.substring(0,word.length()-1);
                        SingleWordDictVo singleWordDictVo = new SingleWordDictVo();
                        singleWordDictVo.setName(ch);
                        singleWordDictVo.setSpecialChar(true);
                        backSingleWordDictList.add(singleWordDictVo);
                        ch = word.substring(word.length()-1, word.length());
                    }

                    SingleWordDictVo singleWordDictVo = new SingleWordDictVo();
                    singleWordDictVo.setSpecialChar(false);
                    singleWordDictVo.setName(word);

                    //是否收藏
                    if(query.getUserId() != null){
                        //考虑放到缓存中，暂时不处理 todo
//                    UserWordDictQuery userWordDictQuery = new UserWordDictQuery();
//                    userWordDictQuery.setUserId(query.getUserId());
//                    userWordDictQuery.setWordId(.getId());
//                    UserWordDict userWordDict = userWordDictService.findOne(userWordDictQuery);
//                    singleWordDictVo.setCollect(userWordDict != null);
                    }
                    singleWordDictList.add(singleWordDictVo);

                    //逆序
                    Collections.reverse(backSingleWordDictList);
                    singleWordDictList.addAll(backSingleWordDictList);
                }

            }

            newDataList.add(subtitleVo);
        }
        return newDataList;
    }

    public List<SubtitleVo> subtitleList(Long contentId,Integer collect,Integer practiceLevel){
        SubtitleQuery subtitleQuery = new SubtitleQuery();
        subtitleQuery.setContentId(contentId);
        subtitleQuery.setOrderByColumn("orderNo");
        subtitleQuery.setAscOrDesc("asc");
        List<SubtitleVo> dataList = this.findAllVo(subtitleQuery);

        List<SubtitleVo> newDataList = new ArrayList<>();
        UserVo loginUser = UserManager.getLoginUser();
        if(loginUser != null){
            //难度  //收藏
            UserSubtitleQuery userSubtitleQuery = new UserSubtitleQuery();
            userSubtitleQuery.setContentId(contentId);
//            userSubtitleQuery.setCollect(collect);
//            userSubtitleQuery.setPracticeLevel(practiceLevel);
            List<UserSubtitle> userSubtitleList = userSubtitleService.findAll(userSubtitleQuery);
            if (CollectionUtils.isNotEmpty(userSubtitleList)) {
                Map<Long, UserSubtitle> userSubtitleMap = userSubtitleList.stream().collect(Collectors.toMap(data -> data.getSubtitleId(), data -> data));
                for (SubtitleVo subtitleVo : dataList) {
                    UserSubtitle userSubtitle = userSubtitleMap.get(subtitleVo.getId());
                    if(userSubtitle != null){
                        subtitleVo.setCollect(userSubtitle.getCollect());
                        subtitleVo.setPracticeLevel(userSubtitle.getPracticeLevel());
                    }
//                    if(collect != null && subtitleVo.getCollect() == null){
//                        continue;
//                    }
//
//                    if(collect != null  && collect.intValue() != subtitleVo.getCollect()){
//                       continue;
//                    }
//                    if(practiceLevel != null && subtitleVo.getPracticeLevel() == null){
//                        continue;
//                    }
//                    if(practiceLevel != null  && practiceLevel.intValue() != subtitleVo.getPracticeLevel()){
//                        continue;
//                    }
//                    newDataList.add(subtitleVo);
                }
            }
        }

        //过滤条件
        dataList = dataList.stream().filter(data->{
            boolean state = true;
            if(collect != null){
                state = collect.intValue() == data.getCollect();
            }
            if(!state){
                return state;
            }
            if(practiceLevel != null){
                state = practiceLevel.intValue() == data.getPracticeLevel();
            }
            return state;
        }).collect(Collectors.toList());

        //重新设置序号
        for (int i = 0; i < dataList.size(); i++) {
            dataList.get(i).setOrderNo(i+1);
        }
        return dataList;
    }


}
